package com.demo.project_template.service.impl;

import com.demo.project_template.constant.CommonConstants;
import com.demo.project_template.entity.Coupon;
import com.demo.project_template.entity.UserCoupon;
import com.demo.project_template.mapper.CouponMapper;
import com.demo.project_template.mapper.UserCouponMapper;
import com.demo.project_template.service.UserCouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.project_template.util.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 用户优惠卷 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2023-06-19 15:56:44
 */
@Service
public class UserCouponServiceImpl extends ServiceImpl<UserCouponMapper, UserCoupon> implements UserCouponService {

    @Resource
    private UserCouponMapper userCouponMapper;
    @Resource
    private CouponMapper couponMapper;

    /**
     * 用户领取优惠券
     *
     * @param userId   用户id
     * @param couponId 优惠券id
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void userReceiveCoupon(Integer userId, Integer couponId) {
        Coupon coupon = couponMapper.selectById(couponId);
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setCouponId(couponId);
        userCoupon.setCloseTime(DateUtil.changeDateByDay(new Date(), coupon.getValidTime()));
        userCoupon.setCouponStatue(CommonConstants.ENABLE);
        userCoupon.setCouponPrice(coupon.getCouponPrice());
        userCoupon.setCouponName(coupon.getCouponName());
        userCoupon.setCouponMinPrice(coupon.getCouponMinPrice());
        userCoupon.setIsDelete("0");
        userCouponMapper.insert(userCoupon);
    }
}
